package net.ncraft.mc.ezframework.core.handler.database;

import com.zaxxer.hikari.HikariDataSource;
import net.ncraft.mc.ezframework.core.annotations.database.*;
import org.bukkit.plugin.java.JavaPlugin;
import org.reflections.Reflections;

import java.lang.reflect.Field;
import java.util.*;

public class DatabaseHandler {

    private static final List<Class> DATASOURCE_CLASSES = new ArrayList<>();
    private static final List<Class> DATABASE_CLASSES = new ArrayList<>();

    private static final Map<String, HikariDataSource> DATA_SOURCES =  new HashMap<>();

    public static void load(JavaPlugin plugin) {
        Reflections reflections = new Reflections(plugin.getClass().getPackageName());
        DATASOURCE_CLASSES.addAll(reflections.getTypesAnnotatedWith(EDataSource.class));
        DATABASE_CLASSES.addAll(reflections.getTypesAnnotatedWith(Database.class));
        registerHandler();
    }
    public static HikariDataSource getDataSource(String name) {
        return DATA_SOURCES.get(name);
    }


    private static void registerHandler() {

        for (Class<? extends EDataSource> datasourceClass : DATASOURCE_CLASSES) {
            EDataSource dataSourceAnn = datasourceClass.getAnnotation(EDataSource.class);

            try {


                Field[] dataSourceInfo = datasourceClass.getDeclaredFields();

                String url = null;
                String username = null;
                String password = null;

                for (Field info : dataSourceInfo) {
                    info.setAccessible(true);
                    if (info.isAnnotationPresent(DatabaseURL.class)) {
                        url = (String) info.get(datasourceClass.newInstance());
                    }
                    if (info.isAnnotationPresent(DatabaseUser.class)) {
                        username = (String) info.get(datasourceClass.newInstance());
                    }
                    if (info.isAnnotationPresent(DatabasePassword.class)) {
                        password = (String) info.get(datasourceClass.newInstance());
                    }
                }

                HikariDataSource dataSource = new HikariDataSource();
                dataSource.setJdbcUrl(url);
                dataSource.setUsername(username);
                dataSource.setPassword(password);
                dataSource.setMaxLifetime(30000);
                DATA_SOURCES.put(dataSourceAnn.value(), dataSource);

            } catch (InstantiationException | IllegalAccessException e) {
                throw new RuntimeException(e);
            }


        }

    }
}
